<?php
	$form = $_POST;
	$hotel = new Hotel();
	$hotel->setname($form['hotel_name']);
	$hotel->setaddress($form['address']);
	$hotel->setlocation($form['location']);
	$hotel->setdescription($form['description']);
	$hotel->setstar($form['star']);
	$hotel->setlatitude_x($form['txt_latx']);
	$hotel->setlatitude_y($form['txt_laty']);
	$hotel->setactive(isset($form['active']) ? 1 : 0);

	$selected_facilities = array();
	foreach ($form as $key => $value)
		if (strpos($key, 'facility_') !== false && $value == 'on') {
			preg_match("#facility_([0-9]*)#", $key, $match);
			if ($match[1])
				$selected_facilities[] = $match[1];
		}
		
	$prefixes = array();
	$prefixes[] = 'tour_price_';
	$prefixes[] = 'tour_ideas_';
	$prefixes[] = 'tour_ads_';
		
	$pic_id = check_and_upload_picture('thumbnail', $form['thumbnail_name'], $_FILES, $prefixes);
	if ($pic_id) {
		// TODO: remove the old one
		if ($hotel_id) {
			$hotel->select($hotel_id);
			$old_pic_id = $hotel->getthm_picture();
			$hotel->setthm_picture($pic_id);
			$hotel->update();
			if ($old_pic_id) {
				$old_pic = new Picture();
				$old_pic->select($old_pic_id);
				$old_pic->deleteAllFiles();
				$old_pic->delete();
			}
		}
		$hotel->setthm_picture($pic_id);
	} elseif ($hotel_id) {
		$tmp_hotel = new Hotel();
		$tmp_hotel->select($hotel_id);
		$hotel->setthm_picture($tmp_hotel->getthm_picture());
	}
		
	if ($hotel_id) { // it's an update action
		$hotel->update($hotel_id);
		$hotel->select($hotel_id);
		// remove all old hotel facilities firstly
		$facilities = HotelFacility::getAllFacilitiesForHotel($hotel_id);
		if (!empty($facilities))
		foreach ($facilities as $facility) {
				$hotel_facility =  HotelFacility::retriveByHotelIdAndFacilityId($hotel_id, $facility->getid());
				$hotel_facility->delete($hotel_facility->getid());
		}
	} else { // it's an create action
		$hotel->insert();
	}
	
	// create new hotel facility relations
	foreach ($selected_facilities as $facility_id) {
		$hotel_facility = new HotelFacility();
		$hotel_facility->sethotel_id($hotel->getid());
		$hotel_facility->setfacility_id($facility_id);
		$hotel_facility->insert();
	}

	$msg = $hotel_id ? "Khách sạn đã được sửa thành công" : "Khách sạn đã được thêm thành công";
	admin_load($msg, "?act=hotels_manager");
?>